package com.pb.infra.taskManage.service;

import com.pb.infra.taskManage.mapper.ProcessManageMapper;
import com.pb.infra.oth.entity.common.Page;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.oth.util.DateTimeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 流程管理
 * @author liaohaoyuan
 * @date 20210501
 */
@Service
public class ProcessManageService {

    /**
     * DAO映射
     */
    @Resource
    private ProcessManageMapper processmanageMapper;

    /**
     * 查询分页数据
     *
     * @param map  查询参数
     * @param page 页码
     * @return
     */
    public Result select(Map<String, Object> map, Page page) {
        Integer pageIndex = Integer.parseInt(map.get("pageIndex").toString());
        Integer pageSize = Integer.parseInt(map.get("pageSize").toString());
        Integer pageEnd = pageSize * pageIndex;
        Integer pageStart = (pageIndex - 1) * pageSize;
        map.put("pageEnd", pageEnd);
        map.put("pageStart", pageStart);
        List<Map<String, Object>> list = processmanageMapper.select(map);
        return Result.ok(processmanageMapper.selectCount(map), list);
    }

    /**
     * 查询流程下拉框数据
     *
     * @return
     */
    public List<Map<String, Object>> getProcedureData() {
        return processmanageMapper.getProcedureData();
    }

    /**
     * 保存或者修改
     *
     * @param paramMap
     * @return
     */
    @Transactional
    public Result save(Map<String, Object> paramMap) throws Exception {
        String sysNm = (String) paramMap.get("procedureNm");
        String effDate = (String) paramMap.get("effectiveDate");
        List<Map<String, Object>> arrData = (List<Map<String, Object>>) paramMap.get("taskData");
        String sysNo = processmanageMapper.selSysNo();
        String lastData = DateTimeUtil.getAddDate(effDate, -1);
        String nextDate = DateTimeUtil.getAddDate(effDate, 1);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysNo", sysNo + "");
        map.put("sysNm", sysNm);
        map.put("lastData", lastData);
        map.put("lastStatus", "S");
        map.put("effDate", effDate);
        map.put("effDateStatus", "S");
        map.put("nextDate", nextDate);
        processmanageMapper.save(map);
        processmanageMapper.insertMaJobCfg(sysNo + "", sysNm);
        for (Map<String, Object> arrDatum : arrData) {
            arrDatum.put("sysNo", sysNo + "");
            processmanageMapper.insertMajob(arrDatum);
            processmanageMapper.insertMaJobRelyCfg(arrDatum);
        }
        return Result.OK_EMPTY;
    }

    /**
     * 修改
     *
     * @param paramMap
     * @return
     */
    public Result update(Map<String, Object> paramMap) {
        processmanageMapper.update(paramMap);
        return Result.OK_EMPTY;
    }

    /**
     * 删除流程数据
     *
     * @param paramList
     * @return
     */
    @Transactional
    public Result delete(List<String> paramList) {
        Integer count = processmanageMapper.selStatus(paramList);
        if (count > 0) {
            return Result.error("-1", "删除失败！有正在运行的任务");
        } else {
            processmanageMapper.delDate(paramList);
            processmanageMapper.delStatus(paramList);
            processmanageMapper.delEvent(paramList);
            processmanageMapper.delRely(paramList);
            processmanageMapper.delJob(paramList);
            processmanageMapper.delMon(paramList);
        }
        return Result.OK_EMPTY;
    }

    /**
     * 启动
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    public Result startUp(Map<String, Object> paramMap) throws Exception {
        String newSysNo = (String) paramMap.get("SYS_NO");
        String dataDate = (String) paramMap.get("DATA_DATE");
        if (processmanageMapper.checkStart(newSysNo) > 0) {
            return Result.error("-1", "新建批次请联系管理员");
        } else {
            if (processmanageMapper.checkMonStart(newSysNo) < 1) {
                return Result.error("-1", "启动之前请先配置重跑区间");
            } else {
                String sysNo = processmanageMapper.checkCfgRunFlag();
                paramMap.put("lastDate", DateTimeUtil.getAddDate(dataDate, -1));
                paramMap.put("nextDate", DateTimeUtil.getAddDate(dataDate, 1));
                if (sysNo != null && !"".equals(sysNo)) {
                    if (processmanageMapper.checkStatuSchedule(sysNo) > 0) {
                        return Result.error("-1", "启动失败，有作业正在运行");
                    } else {
                        Map<String, Object> map = new HashMap<>();
                        map.put("sysNo", sysNo);
                        map.put("fal", 2);
                        processmanageMapper.startTask(map);
                        map.put("sysNo", newSysNo);
                        map.put("fal", 1);
                        processmanageMapper.startTask(map);
                        processmanageMapper.editStartTask(paramMap);
                        processmanageMapper.delStatusSchedule(newSysNo);
                        return Result.ok("启动成功");
                    }
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("sysNo", newSysNo);
                    map.put("fal", 1);
                    processmanageMapper.startTask(map);
                    processmanageMapper.editStartTask(paramMap);
                    processmanageMapper.delStatusSchedule(newSysNo);
                }
            }
        }
        return Result.OK_EMPTY;
    }

    /**
     * 暂停
     * @param paramMap
     * @return
     */
    public Result stopTasks(Map<String, Object> paramMap) {
        String sysNo = (String) paramMap.get("sysNo");
        if (processmanageMapper.checkStart(sysNo) > 0) {
            return Result.error("-1", "新建批次请联系管理员");
        }
        processmanageMapper.stopTask(sysNo);
        int i = processmanageMapper.checkStatuSchedule(sysNo);
        if (i > 0) {//正在运行的作业
            ThreadY ty = new ThreadY();
            ty.setSysNo(sysNo);
            Thread thread = new Thread(ty);
            try {
                thread.start();
            } catch (Exception e) {
                //有任何异常关闭线程
                thread.interrupt();
            }
            return Result.ok("有作业已在运行中，已暂停后续作业");
        } else {
            processmanageMapper.editTask(sysNo);
            return Result.ok("暂停成功");
        }

    }

    /**
     * 内部类（暂停之前查询）
     */
    public class ThreadY implements Runnable {
        private boolean result = true;
        String sysNo;

        public void setSysNo(String sysNo) {
            this.sysNo = sysNo;
        }
        @Override
        public void run() {
            while (result) {
                try {
                    Thread.sleep(5 * 1000);
                    int i = processmanageMapper.checkStatuSchedule(sysNo);
                    if (i < 1) {
                        processmanageMapper.editTask(sysNo);
                        Map<String, Object> map = new HashMap<>();
                        map.put("sysNo", sysNo);
                        map.put("fal", 2);
                        processmanageMapper.startTask(map);//修改批次为不可运行
                        result = false;
                    }
                } catch (InterruptedException e) {
                    result = false;
                }
            }
        }
    }

    /**
     * 继续
     * @param paramMap
     * @return
     */
    @Transactional
    public Result continueTasks(Map<String,Object> paramMap){
        String sysNo = (String) paramMap.get("sysNo");
        if (processmanageMapper.checkStart(sysNo)>0){
            return Result.error("-1","新建批次请联系管理员");
        }else if (processmanageMapper.checkTaskSysStatus(sysNo)<1){
            return  Result.error("-1","此作业不需要继续运行");
        }else {
            processmanageMapper.continueTask(sysNo);
            Map<String,Object> map = new HashMap<>();
            map.put("sysNo", sysNo);
            map.put("fal", 1);
            processmanageMapper.startTask(map);
        }
        return Result.ok("继续任务成功");
    }

    /**
     * 重启
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Transactional
    public Result rebootings(Map<String,Object> paramMap)throws Exception{
        String sysNo = (String) paramMap.get("SYS_NO");
        if (processmanageMapper.checkStart(sysNo)>0){
            return Result.error("-1","新建批次，请联系管理员");
        } else {
            String dataDate = (String) paramMap.get("DATA_DATE");
            processmanageMapper.delSchedule(sysNo, dataDate);
            String date=DateTimeUtil.getAddDate(dataDate, -1);
            String lastDate=DateTimeUtil.getAddDate(date, -1);
            processmanageMapper.upDateCtl(sysNo,date,lastDate ,dataDate);//修改调度日期控制表
            Map<String,Object> map = new HashMap<>();
            map.put("sysNo", sysNo);
            map.put("fal", 1);
            processmanageMapper.startTask(map);//修改批次未可运行
        }
        return Result.ok("重启启动成功");
    }

    /**
     * 任务数据
     * @param paramMap
     * @return
     */
    @Transactional
    public  Result setIntervalDat(Map<String,Object> paramMap){
        processmanageMapper.deleteSchedule(paramMap);
        String dayLast = DateTimeUtil.getDayLast((String)paramMap.get("startTime"));
        String daylastDay = DateTimeUtil.getDayLast(dayLast);
        paramMap.put("dayLast",dayLast);
        paramMap.put("daylastDay",daylastDay);
        processmanageMapper.editDateCtl(paramMap);
        List<String> paramList = new ArrayList<String>();
        paramList.add((String) paramMap.get("sysNo"));
        processmanageMapper.delMon(paramList);
        List<String> list = DateTimeUtil.betweenDays((String) paramMap.get("startTime"),(String) paramMap.get("endTime"));
        for (String str : list) {
            paramMap.put("date",str);
            processmanageMapper.saveStatus(paramMap);
        }
        return Result.OK_EMPTY;
    }
}

